﻿using DotNet.Utilities;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace _163News
{
    internal class _163NewsWebProtocol
    {
        public _163NewsWebProtocol(string cookie)
        {
            this.Cookie = cookie;
        }

        public _163NewsWebProtocol()
        {
        }

        public string Cookie { get; set; }
        public string ProductKey { get; set; }

        public static List<string> CollectNewsUrl(string url)
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem
            {
                URL = url,
            };
            HttpResult res = http.GetHtml(item);

            // 判断是否 频道链接 or 滚动新闻链接
            Match m0 = Regex.Match(res.Html, "http://.*?news_json\\.js");
            if (m0.Success)
            {
                // 滚动新闻
                item.URL = m0.Groups[0].Value;
                res = http.GetHtml(item);
            }

            MatchCollection mc = Regex.Matches(res.Html, "http://news\\.163\\.com/\\d{2}/\\d{4}/\\d{2}/\\w{16}\\.html");
            Console.WriteLine(mc.Count);
            List<string> list = new List<string>();
            foreach (Match m in mc)
            {
                list.Add(m.Groups[0].Value);
            }
            return list;
        }

        public bool Comment(string url, string content)
        {
            //http://comment.news.163.com/api/v1/products/a2869674571f77b5a0867c3d71db5856/threads/BLU811R100014PRF/comments?ibc=newspc
            //content=%E5%82%BB%E5%95%8A%EF%BC%81%E5%85%88%E7%A0%8D%E4%B8%A4%E6%A3%B5%E6%A0%91%EF%BC%8C%E8%B0%81%E6%9D%A5%E7%BD%9A%E6%AC%BE%E5%B0%B1%E6%89%BE%E8%B0%81%E3%80%82%E6%B2%A1%E4%BA%BA%E7%AE%A1%E5%B0%B1%E5%85%A8%E7%A0%8D%E4%BA%86%E5%8D%96%E9%92%B1&parentId=&board=news_guonei8_bbs

            //http://comment.news.163.com/news_guonei8_bbs/BM1124LB00014PRF.html
            //http://sdk.comment.163.com/api/v1/products/a2869674571f77b5a0867c3d71db5856/threads/BM1124LB00014PRF/comments?ibc=jssdk&_=1462190719095

            GetProductKey();

            // GetDocId
            Match m = Regex.Match(url, "/(\\w{16}).html");
            if (!m.Success) return false;
            string docId = m.Groups[1].Value;

            //GetBoard
            //m = Regex.Match(url, "/(.*?)/" + docId);
            //if (!m.Success) return;
            //string board = m.Groups[1].Value;

            HttpItem item = new HttpItem
            {
                URL = $"http://comment.news.163.com/api/v1/products/{ProductKey}/threads/{docId}/comments",
                Method = "POST",
                Postdata = $"content={Uri.EscapeDataString(content)}&parentId=",
                ContentType = "application/x-www-form-urlencoded",
                Cookie = this.Cookie,
            };
            HttpHelper http = new HttpHelper();
            HttpResult res = http.GetHtml(item);
            //Console.WriteLine(res.Html);

            //{"against":0,"anonymous":false,"buildLevel":1,"commentId":1398938131,"content":"习总书记：“您用事实告诉了中国人民，有您在中国就有希望，热爱、支持您，愿意在您的引领下，实现中国梦”。","createTime":"2016-05-01 12:47:03","favCount":0,"ip":"49.67.*.*","isDel":false,"postId":"BLU811R100014PRF_1398938131","shareCount":0,"source":"wb","user":{"avatar":"","id":"dGxzaWV1Y25AMTYzLmNvbQ==","location":"江苏省南通市","nickname":"tlsieucn","userId":98739756},"vote":0}

            return (res.Html.IndexOf("{\"against\":0,") != -1);
        }

        public bool Login(string mail, string pwd)
        {
            #region 登陆POST

            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem
            {
                URL = $"https://mail.163.com/entry/cgi/ntesdoor?funcid=loginone&language=-1&passtype=1&iframe=1&product=mail163&from=web&df=email163&race=423_39_51_gz&module=&uid={mail}&style=-1&net=t&skinid=null",
                Method = "POST",
                Postdata = $"username={mail}&url2=http%3A%2F%2Femail.163.com%2Ferrorpage%2Ferror163.htm&savalogin=0&password={pwd}",
                ContentType = "application/x-www-form-urlencoded",
            };
            HttpResult res = http.GetHtml(item);

            #endregion 登陆POST

            #region 处理POST返回数据

            //Console.WriteLine(res.Html);
            Match m = Regex.Match(res.Html, "sid=(.*?)&");
            if (!m.Success) return false;
            this.Cookie = res.Cookie;
            string sid = m.Groups[1].Value;
            //Console.WriteLine(sid);
            //Console.WriteLine(this.Cookie);
            return true;

            #endregion 处理POST返回数据
        }

        private void GetProductKey()
        {
            if (!string.IsNullOrEmpty(ProductKey)) return;
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem
            {
                URL = "http://ent.163.com/16/0503/15/BM5D9VUO00031H2L.html",
                Cookie = this.Cookie,
            };
            HttpResult res = http.GetHtml(item);
            Match m = Regex.Match(res.Html, "\"productKey\" : \"(\\w{32})\"");
            
            this.ProductKey = m.Groups[1].Value;
            
        }
    }
}